<?php
/**
 * @Author: liuhongbin
 * @Email: 514660094@qq.com
 * @Date: 2019-02-12 16:15:10
 * @Description:用户对应应用权限
 * @LastEditors: liuhongbin
 */

namespace app\controller\adminapi\addonAuth;

use app\common\model\addon\Addons;
use hiduoke\services\FormBuilder as Form;
use think\App;
use app\common\model\user\User as UserModel;
use app\common\controller\AdminController;
use app\common\model\addonAuth\UserAddon;
use app\common\model\addonAuth\UserAddonGroup;
use think\Request;

class UserAddonAuth extends AdminController
{
    /**
     * 用户应用模型
     * @var UserAddon
     */
    private $UserAddon;

    /**
     * 用户应用组模型
     * @var UserAddonGroup
     */
    private $UserAddonGroup;

    /**
     * 用户模型
     * @var UserModel
     */
    private $User;


    public function __construct(App $app, UserAddon $UserAddon, UserAddonGroup $UserAddonGroup, UserModel $User)
    {
        parent::__construct($app);
        $this->UserAddon = $UserAddon;
        $this->UserAddonGroup = $UserAddonGroup;
        $this->User = $User;
    }

    /**
     * 获取用户应用权限表单
     * @param $uid
     * @return \think\response\Json
     */
    public function getUserAddonAuthForm($uid)
    {
        $Addons = new Addons();
        //创建表单
        $form = Form::createForm("/adminapi/addonGroup/user/setUserAddonAuth")->setMethod("POST");
        $user = $this->User::withSearch(['uid'], ['uid' => $uid])->findOrEmpty();
        $rule[] = Form::input('uid', '用户ID', $user->uid)->disabled(true);
        $rule[] = Form::input('username', '登录账号', $user->username)->disabled(true);
        $rule[] = Form::dkAddonGroupSelect("addon_groups", "扩展应用组", $this->UserAddonGroup->getUserAddonGroupForSelect($uid))->appendToBody()->info("添加当前用户可额外使用的应用组");
        $addons = $this->UserAddon->getAddons($uid);
        $addonsExplain = $Addons->getAddonsByFormDataAddons($addons);
        $rule[] = Form::dkAddonSelect("addons", "扩展应用", $addons)
            ->addonsExplain($addonsExplain)
            ->appendToBody()
            ->info('添加当前用户额外的应用权限');
        $form->setTitle("用户应用权限")->setRule($rule);
        return $this->success("", Form::getFormData($form));
    }

    /**
     * 设置用户应用权限
     * @param Request $request
     * @return \think\response\Json
     */
    public function setUserAddonAuth(Request $request)
    {
        $formData = $request->post("formData", []);
        $uid = $formData['uid'];
        $user = $this->User->where(['uid' => $uid])->find();
        if (!$user) {
            return $this->error("用户不存在");
        }
        //用户扩展应用
        $this->UserAddon->saveAddons($uid, $formData['addons']);
        //用户扩展应用组
        $this->UserAddonGroup->saveAddonGroupIdsByAddonGroups($uid, $formData['addon_groups']);
        return $this->success("保存成功");
    }
}
